const { Service } = require("egg");

class AclService extends Service {
    /**
     * 根据查询条件，查询某个权限
     * @param {*} type
     * @param {*} path
     * @param {*} method
     */
    async findByQuery(type, path, method) {
        let res = await this.app.mysql.query(
            "select * from acl where type = ? and path = ? and method = ? limit 0, 1",
            [type, path, method]
        );
        return res[0];
    }

    /**
     * 根据类型，查询权限列表
     * @param {number} type 权限类型
     */
    async readListByQuery(type) {
        let sql = "select * from acl";
        let params = [];
        if (type) {
            sql += " where type = ?";
            params.push(type);
        }
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 添加权限
     * @param {obejct} param0
     */
    async add({ name, type, path = "", method = "" }) {
        // 如果已存在，就不能添加了
        let record = await this.findByQuery(type, path, method);
        if (record) {
            this.ctx.cast(403, "该权限已存在");
        }
        // 添加
        let res = await this.app.mysql.query(
            "insert into acl (id, name, type, path, method) values (?, ?, ?, ?, ?)",
            [this.ctx.helper.uuid(), name, type, path, method]
        );
        // 返回执行结果
        return res;
    }

    /**
     * 根据用户id，查找权限
     * @param {number} uid 用户id
     */
    async readByUid(uid) {
        let sql = `
            select a.id
            from user as u
            join r_user_role as rur on u.id = rur.uid
            join r_role_acl as rra on rur.rid = rra.rid
            join acl as a on rra.aid = a.id and a.type = 1
            where u.id = ?;        
        `;
        let params = [uid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }
}

module.exports = AclService;
